package com.web.quartz;

import lombok.extern.slf4j.Slf4j;
import org.quartz.Scheduler;
import org.springframework.beans.BeansException;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;

@Slf4j
@Component
public class JobInitService implements CommandLineRunner, ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        JobInitService.applicationContext = applicationContext;
    }

    @Override
    public void run(String... args) {
        if (applicationContext != null) {
            Map<String, DefaultJob> dnicJobMap = applicationContext.getBeansOfType(DefaultJob.class);
            dnicJobMap.forEach((k, v) -> v.execute());
            log.info("正在创建定时任务....");
            Map<String, ScheduleJob> scheduleJobMap = applicationContext.getBeansOfType(ScheduleJob.class);
            Scheduler scheduler = applicationContext.getBean(Scheduler.class);
            scheduleJobMap.forEach((k, v) -> ScheduleUtils.createJob(scheduler, v));
            log.info("创建定时任务完毕");
        }

    }


}
